package com.hjt.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.hjt.common.constant.AuthConstant;
import com.hjt.common.to.member.UserLoginTo;
import com.hjt.common.utils.R;
import com.hjt.gulimall.auth.feign.MemberFeignService;
import com.hjt.gulimall.auth.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:97007
 * @date:2021/9/28 22:37
 */
@Controller
public class LoginController {


    @Autowired
    MemberFeignService memberFeignService;


    // 登录页
    @GetMapping({"/","/login.html"})
    public String index(HttpSession session) {
        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        if (attribute != null) {
            // 已登录，跳转到首页
            return "redirect:http://gulimall.com";
        }
        return "index";
    }

    // 登录接口
    @PostMapping("/login")
    public String login(@Valid UserLoginVo loginVo, BindingResult bindingResult, RedirectAttributes model, HttpSession session) {

        // 校验登录信息
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            model.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com";
        }

        // 远程调用登录服务
        R result = memberFeignService.login(loginVo);

        if (result.getCode() == 0) {
            UserLoginTo data = result.getData(new TypeReference<UserLoginTo>() {});
            session.setAttribute(AuthConstant.LOGIN_USER, data);
            // 登录成功
            return "redirect:http://gulimall.com";
        } else {
            // 登录失败添加错误信息
            Map<String, String> map = new HashMap<>();
            map.put("msg",result.getMessage());
            model.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com";
        }
    }


}
